package myta.bean;

import javax.faces.component.html.HtmlInputSecret;
import javax.faces.component.html.HtmlInputText;

import myta.model.DataRow;
import myta.model.DataTable;
import myta.service.Command;
import myta.service.Database;
import myta.service.SQLexec;
import myta.service.Utility;

public class LoginAdmin {
	private HtmlInputText txtusername;
	private HtmlInputSecret txtpassword;
	
	public LoginAdmin() {
		try {
			if(Database.dbConnection == null){
				Database.connectToDatabase();
			}
			
			txtusername = new HtmlInputText();
			txtpassword = new HtmlInputSecret();
		} catch (Exception e) {
			Utility.showMessage(e.getMessage());
		}
	}
	
	public String loginAction(){
		try {
			String sql = "select * from admin where username = ? and passwd = ?";
			Command command = SQLexec.makeCommand(sql);
			command.setObject(1, txtusername.getValue().toString());
			command.setObject(2, txtpassword.getValue().toString());
			DataTable datatable = command.executeQuery();
			
			if(datatable.getRowCount() > 0){
				Session s = (Session)Utility.getBean("sessionBean");
				
				DataRow datarow = datatable.getRow(0);
				s.setIdadmin(datarow.getString("idadmin"));
				s.setNamaadmin(datarow.getString("nama"));
				s.setLogin(true);
			}else{
				throw new Exception("Username atau Password salah! mohon ulangi lagi");
			}
			
			return "admin.jsf?faces-redirect=true";
		} catch (Exception e) {
			Utility.showMessage("Login error : " + e.getMessage());
			return "";
		}
	}
	
	public HtmlInputText getTxtusername() {
		return txtusername;
	}
	public void setTxtusername(HtmlInputText txtusername) {
		this.txtusername = txtusername;
	}
	public HtmlInputSecret getTxtpassword() {
		return txtpassword;
	}
	public void setTxtpassword(HtmlInputSecret txtpassword) {
		this.txtpassword = txtpassword;
	}
}
